package com.topscomm.main.config;

import com.topscomm.basic.BaseDataSource;
import com.topscomm.tap.mybatis.SqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
public class MpmDataSourceConfig {
	@Value("${DefaultDataBaseTypeNameMPM}")
	private String defaultDataBaseTypeName;

	@Bean(name = "mpmDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.druid.mpmdatabase")
	public DataSource dataSource() {
		return new BaseDataSource();
	}

	@Bean(name = "mpmSqlSessionFactory")
	public SqlSessionFactory sqlSessionFactoryMpm(@Qualifier("mpmDataSource") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		bean.setMapperLocations(new PathMatchingResourcePatternResolver()
				.getResources("classpath*:config/mybatis/*/" + defaultDataBaseTypeName + "/**/ibatis_*.xml"));
		bean.setConfigLocation(new PathMatchingResourcePatternResolver()
				.getResource("classpath:config/mybatis/" + defaultDataBaseTypeName + "/sqlMapConfig.main.xml"));
		return bean.getObject();
	}

	@Bean(name = "mpmTransactionManager")
	public DataSourceTransactionManager transactionManager(@Qualifier("mpmDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "mpmSqlSessionTemplate")
	public SqlSessionTemplate sqlSessionTemplate(@Qualifier("mpmSqlSessionFactory") SqlSessionFactory sqlSessionFactory)
			throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}
